package org.geomesa.example.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureIterator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GridImageMappingManager {

    private Connection connection;
    private Admin admin;
    private TableName invertIndexTaleName;
    private final String COLUMN_FAMILY = "img";
    private TableName forwardIndexTableName;
    private final String FORWARD_COLUMN_FAMILY = "grid";


    /**
     * 初始化HBase连接和表，如果表不存在则创建
     *
     * @param zookeeperQuorum HBase集群ZK地址，比如 "localhost" 或 "zk1,zk2,zk3"
     * @param invertIndexTaleNameStr    表名
     * @param forwardIndexTableNameStr    表名
     * @throws IOException
     */
    public void init(String zookeeperQuorum, String invertIndexTaleNameStr, String forwardIndexTableNameStr) throws IOException {
        Configuration config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", zookeeperQuorum);
        // 其他HBase配置根据需要补充
        connection = ConnectionFactory.createConnection(config);
        admin = connection.getAdmin();
        invertIndexTaleName = TableName.valueOf(invertIndexTaleNameStr);

        if (!admin.tableExists(invertIndexTaleName)) {
            // 创建表和列族
            HTableDescriptor tableDescriptor = new HTableDescriptor(invertIndexTaleName);
            HColumnDescriptor columnDescriptor = new HColumnDescriptor(COLUMN_FAMILY);
            tableDescriptor.addFamily(columnDescriptor);
            admin.createTable(tableDescriptor);
            System.out.println("反向索引表 " + invertIndexTaleNameStr + " 创建成功.");
        } else {
            System.out.println("反向索引表 " + invertIndexTaleNameStr + " 已存在.");
        }

        forwardIndexTableName = TableName.valueOf(forwardIndexTableNameStr);
        if (!admin.tableExists(forwardIndexTableName)) {
            HTableDescriptor tableDescriptor = new HTableDescriptor(forwardIndexTableName);
            HColumnDescriptor columnDescriptor = new HColumnDescriptor(FORWARD_COLUMN_FAMILY);
            tableDescriptor.addFamily(columnDescriptor);
            admin.createTable(tableDescriptor);
            System.out.println("正向索引表 " + forwardIndexTableNameStr + " 创建成功.");
        } else {
            System.out.println("正向索引表 " + forwardIndexTableNameStr + " 已存在.");
        }
    }


    /**
     * 批量插入影像-网格覆盖关系
     *
     * @param imgId    影像ID，比如 "img_1"
     * @param gridKeys 覆盖的网格ID列表，比如 ["grid_0_0", "grid_0_1"]
     * @throws IOException
     */
    public void insertInvertIndex(String imgId, List<String> gridKeys) throws IOException {
        Table table = connection.getTable(invertIndexTaleName);

        try {
            for (String gridKey : gridKeys) {
                Put put = new Put(Bytes.toBytes(gridKey));
                String column = "img_" + imgId; // 列名示例 img_img_1
                put.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes(column), Bytes.toBytes("true"));
                table.put(put);
                System.out.println("插入: 网格 " + gridKey + " -> 影像 " + imgId);
            }
        } finally {
            table.close();
        }
    }

    public void insertForwardIndex(String imgId, List<String> gridKeys) throws IOException {
        Table table = connection.getTable(forwardIndexTableName);
        try {
            Put put = new Put(Bytes.toBytes("img_" + imgId));
            for (String gridKey : gridKeys) {
                String column = "grid:" + gridKey;
                String value = computeGridWindow(gridKey); // TODO 后续可用方法计算真实的 window 像素范围
                put.addColumn(Bytes.toBytes(FORWARD_COLUMN_FAMILY), Bytes.toBytes(column), Bytes.toBytes(value));
            }
            table.put(put);
            System.out.println("正向索引插入完成: 影像 " + imgId + " 包含网格 " + gridKeys.size() + " 个");
        } finally {
            table.close();
        }
    }

    /**
     * 关闭资源
     *
     * @throws IOException
     */
    public void close() throws IOException {
        if (admin != null) admin.close();
        if (connection != null) connection.close();
    }

    // 你需要自己实现或者调用已有代码实现
    // 这个方法输入影像的经纬度范围，返回覆盖的gridKey列表
    public List<String> getCoveredGridKeys(double minLon, double minLat, double maxLon, double maxLat) {
        List<String> result = new ArrayList<>();
        DataStore dataStore = null;
        try {
            // 1. 构造GeoMesa DataStore参数（以HBase为例，参数需根据实际情况调整）
            Map<String, String> params = new HashMap<>();
            params.put("hbase.zookeepers", "localhost:2181"); // 替换为你的zookeeper地址
            params.put("hbase.catalog", "globalgrid2_8"); // 替换为你的表名

            dataStore = DataStoreFinder.getDataStore(params);
            if (dataStore == null) {
                throw new RuntimeException("无法连接GeoMesa HBase DataStore");
            }

            // 2. 构造BBOX CQL
            String cql = String.format("BBOX(geom, %f, %f, %f, %f)", minLon, minLat, maxLon, maxLat);
            Query query = new Query("custom_polygon", ECQL.toFilter(cql), new String[]{"name"});

            // 3. 查询并收集结果
            try (SimpleFeatureIterator it = dataStore.getFeatureSource("custom_polygon").getFeatures(query).features()) {
                while (it.hasNext()) {
                    result.add((String) it.next().getAttribute("name"));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error in getCoveredGridKeys", e);
        } finally {
            if (dataStore != null) {
                dataStore.dispose();
            }
        }
        return result;
    }

    private String computeGridWindow(String gridKey) {
        // TODO: 计算该网格在影像中的行列像素范围
        return "[0,0,0,0]";
    }


    // 测试用例示范
    public static void main(String[] args) throws IOException {
        GridImageMappingManager manager = new GridImageMappingManager();

        String zkQuorum = "localhost:2181";

        String invertIndexTaleName = "globalgrid2_8_invert_index";
        String forwardIndexTableName = "globalgrid2_8_forward_index";

        manager.init(zkQuorum, invertIndexTaleName, forwardIndexTableName);

        // 假设有一张影像 img_1 覆盖的范围：
        double minLon = 138.0;
        double minLat = 25.0;
        double maxLon = 140.0;
        double maxLat = 30.0;

        List<String> coveredGrids = manager.getCoveredGridKeys(minLon, minLat, maxLon, maxLat);

        // 插入覆盖关系
        manager.insertInvertIndex("1", coveredGrids);
        // 正向索引插入
        manager.insertForwardIndex("1", coveredGrids);

        manager.close();
    }
}
